package com.alibaba.cirtus.ots.application.adapter.ability.facade.serviceV2.sap;

import com.alibaba.cirtus.ots.application.adapter.ability.facade.serviceV2.common.WarehousePilotService;
import com.alibaba.cirtus.ots.application.adapter.ability.facade.serviceV2.sap.dto.QueryCustomerResponseDTO;
import com.alibaba.cirtus.ots.application.adapter.ability.model.enums.BusinessUnitEnum;
import com.alibaba.cirtus.ots.application.adapter.ability.model.enums.MnSAPStatus;
import com.alibaba.cirtus.ots.application.adapter.ability.utils.ResponseUtil;
import com.alibaba.citrus.cr.common.enums.ordercenter.OrderCategoryEnum;
import com.alibaba.citrus.cr.common.enums.ordercenter.OrderChannelEnum;
import com.alibaba.citrus.ots.common.annotation.ProcessInvoker;
import com.alibaba.citrus.ots.common.exception.FunctionException;
import com.alibaba.citrus.ots.common.lock.RedisLock;
import com.alibaba.citrus.ots.common.util.DateUtils;
import com.alibaba.citrus.ots.common.util.IntegrateUtils;
import com.alibaba.citrus.ots.common.util.SapAndCrmFieldDealUtils;
import com.alibaba.citrus.ots.common.util.TimeUtil;
import com.alibaba.cz.base.tool.DateFormatUtil;
import com.alibaba.cz.base.tool.UUIDUtil;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.middleware.cache.runtime.service.EpochCacheService;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.bcorder.model.dto.*;
import com.epoch.app.bcorder.service.BaseDataService;
import com.epoch.app.bcorder.service.UnifiedInventoryService;
import com.epoch.app.bcots.contants.BcOtsConstants;
import com.epoch.app.crplatformenhance.api.organizationquery.service.OrganizationQueryService;
import com.epoch.app.crplatformenhance.domain.customeraddress.dto.CustomerAddressLoadListRequest;
import com.epoch.app.crplatformenhance.domain.customeraddress.model.CustomerAddress;
import com.epoch.app.crplatformenhance.domain.customeraddress.service.CustomerAddressService;
import com.epoch.app.crplatformenhance.interfacedatasyncconfigquery.service.InterfaceDataSyncConfigQueryService;
import com.epoch.app.crplatformenhance.model.dto.BatchQueryAddress2Request;
import com.epoch.app.crplatformenhance.model.dto.BatchQueryAddress2Response;
import com.epoch.app.crplatformenhance.model.dto.DataCheckRequest;
import com.epoch.app.crplatformenhance.model.enums.OrderTypeEnum;
import com.epoch.app.crplatformenhance.sdo.CustomerAddressSDO;
import com.epoch.app.crplatformenhance.service.CrPlatformEnhanceService;
import com.epoch.app.crunifiedinventory.api.allocateapplyorderread.dto.GetAllocateApplyOrderIdByOutAllocateApplyOrderIdRequest;
import com.epoch.app.crunifiedinventory.api.allocateapplyorderread.service.AllocateApplyOrderReadService;
import com.epoch.app.crunifiedinventory.api.allocateapplyorderwrite.service.AllocateApplyOrderWriteService;
import com.epoch.app.crunifiedinventory.api.forecastwarehouse.dto.QueryWarehouseByFactoryCodeAndWarehouseCodeRequest;
import com.epoch.app.crunifiedinventory.api.forecastwarehouse.service.ForecastWarehouseService;
import com.epoch.app.crunifiedinventory.dto.request.QueryAllocateApplyOrderRequest;
import com.epoch.app.crunifiedinventory.dto.response.AllocateApplyOrderDetailDTO;
import com.epoch.app.crunifiedinventory.model.dto.AllocateApplyOrderDetailCreateDTO;
import com.epoch.app.crunifiedinventory.model.dto.AllocateApplyOrderUpdateDTO;
import com.epoch.app.crunifiedinventory.model.dto.WarehouseInfoDTO;
import com.epoch.app.crunifiedinventory.sdo.enums.DocumentTypeEnum;
import com.epoch.app.mnordercenter.forecastordergroup.service.ForecastOrderGroupService;
import com.epoch.app.mnordercenter.model.dto.CreateForecastDTO;
import com.epoch.app.mnordercenter.model.dto.CreateForecastDetailDTO;
import com.epoch.app.mnordercenter.model.dto.ForecastBizAsyncResponse;
import com.epoch.app.mnordercenter.model.dto.ForecastOrderBizBatchCreateRequest;
import com.epoch.app.otsapplicationadaptersdk.contants.OtsApplicationAdapterSdkConstants;
import com.epoch.app.otsapplicationadaptersdk.model.dto.*;
import com.epoch.app.otsapplicationadaptersdk.model.enums.RetryStatus;
import com.epoch.app.otsapplicationadaptersdk.model.enums.SapApiCode;
import com.epoch.app.otsapplicationadaptersdk.sap.*;
import com.epoch.app.otsapplicationadaptersdk.sapretrywrite.service.SapRetryWriteService;
import com.epoch.app.otsapplicationadaptersdk.sapv2.mnsapif007v2.service.MnSapIf007V2Service;
import com.epoch.app.otsapplicationadaptersdk.service.BcService;
import com.epoch.app.otsapplicationadaptersdk.service.OtsApplicationAdapterSdkService;
import com.epoch.app.otsplatformenhance.dictionaryquery.service.DictionaryQueryService;
import com.epoch.app.otsplatformenhance.model.dto.QueryDictionaryRequest;
import com.epoch.app.otsplatformenhance.sdo.DictionarySDO;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author:
 * @description: sap请求平台同步调拨单创建 F-F1
 *  SAP计划调拨预报单/销售预报单明细信息回传中台（创建、更改、关闭）
 * @date: 2021年09月27日 16:58
 **/
@Component
@Primary
public class MnSapIf007V2ServiceImpl implements MnSapIf007V2Service {
    private final Log log = Log.getLogger(MnSapIf007V2Service.class);

    @Autowired
    private UnifiedInventoryService unifiedInventoryService;
    @Resource
    private ForecastWarehouseService forecastWarehouseService;
    @Resource
    private AllocateApplyOrderWriteService allocateApplyOrderWriteService;
    @Resource
    private AllocateApplyOrderReadService allocateApplyOrderReadService;
    @Resource
    private CrPlatformEnhanceService otsPlatformEnhanceService;
    @Autowired
    private InterfaceDataSyncConfigQueryService interfaceDataSyncConfigQueryService;
    @Resource
    private BaseDataService baseDataService;
    @Resource
    private SapRetryWriteService sapRetryWriteService;
    @Resource
    private EpochCacheService epochCacheService;
    @Resource
    private ForecastOrderGroupService forecastOrderGroupService;
    @Resource
    private OtsApplicationAdapterSdkService otsApplicationAdapterSdkService;
    @Resource
    private WarehousePilotService warehousePilotService;
    @Autowired
    private OrganizationQueryService organizationQueryService;
    @Resource
    private CustomerAddressService customerAddressService;
    @Resource
    private BcService bcService;
    @Resource
    private DictionaryQueryService dictionaryQueryService;
    private static final String FORECAST_ORDER_CACHE_KEY = "FORECAST_ORDER_CACHE_KEY_";
    //设置sap过期时间为
    private static final Long SAP_TIMESTAMP_CACHE_EXPIRE = 60 * 60 * 24 * 100L;
    private static final String DEFAULT_INVENTORY_LOCATION = "defaultInventoryLocation";
    @Value("${ots.checkTimestamp:0}")
    private boolean checkTimestamp;

    @Override
    @ProcessInvoker(remark = "MnSapIf007Service", errorCode = "OTS-02-007-00-16-999", printLog = true)
    public MnSapCommResponse externalSyncUpdateForecast(MnSapIf007Request mnSapIf007Request) {
        log.info("MnSapIf007Service externalSyncUpdateForecast param:{}", JSON.toJSONString(mnSapIf007Request));
        MnSapCommResponse mnSapCommResponse = new MnSapCommResponse();
        //1.获取入参值
        MnSapIf007SDO mnSapIf007SDO = mnSapIf007Request.getData();
        try (RedisLock lock = new RedisLock(BcOtsConstants.REDIS_CACHE_CODE(),"allocateApplyOrderUpdate_" + mnSapIf007SDO.getHeaderKey(),5 * 60 * 1000,10 * 60 * 1000)){
            if (!lock.lock()) {
                MnSapCommSDO mnSapCommSDO = new MnSapCommSDO();
                mnSapCommSDO.setHeaderKey(mnSapIf007SDO.getHeaderKey());
                mnSapCommSDO.setStatus(MnSAPStatus.ERROR.getCode());
                mnSapCommSDO.setMessage("获取分布式锁失败");
                mnSapCommResponse.setData(Lists.newArrayList(mnSapCommSDO));
                saveSapRetry(mnSapIf007Request,"获取分布式锁失败");
                return success(mnSapIf007Request);
            }
            if (Objects.isNull(mnSapIf007SDO)){
                mnSapIf007SDO = IntegrateUtils.safeGetMessageData(MnSapIf007SDO.class);
            }
            MessageHeaderSDO messageHeader = mnSapIf007Request.getMessageHeader();
            if (Objects.isNull(messageHeader)){
                messageHeader = IntegrateUtils.safeGetMessageHeader(MessageHeaderSDO.class);
            }
            if (Objects.nonNull(messageHeader)){
                mnSapCommResponse.setInterfacePath(messageHeader.getInterfacePath());
                mnSapCommResponse.setMessageId(messageHeader.getMessageId());
            }

            //校验调拨预报单是否为空
            if (Objects.isNull(mnSapIf007SDO)){
                MnSapCommSDO mnSapCommSDO = new MnSapCommSDO();
                mnSapCommSDO.setHeaderKey(mnSapIf007SDO.getHeaderKey());
                mnSapCommSDO.setStatus(MnSAPStatus.ERROR.getCode());
                mnSapCommSDO.setMessage("调拨预报单信息不能为空");
                mnSapCommResponse.setData(Lists.newArrayList(mnSapCommSDO));
                saveSapRetry(mnSapIf007Request,"调拨预报单信息不能为空");
                return mnSapCommResponse;
            }
            //校验预报单明细货品是否为空
            if (CollectionUtils.isEmpty(mnSapIf007SDO.getItems())){
                MnSapCommSDO mnSapCommSDO = new MnSapCommSDO();
                mnSapCommSDO.setHeaderKey(mnSapIf007SDO.getHeaderKey());
                mnSapCommSDO.setStatus(MnSAPStatus.ERROR.getCode());
                mnSapCommSDO.setMessage("调拨预报单明细信息不能为空");
                mnSapCommResponse.setData(Lists.newArrayList(mnSapCommSDO));
                saveSapRetry(mnSapIf007Request,"调拨预报单明细信息不能为空");
                return mnSapCommResponse;
            }
            //处理送达方和售达方前置0
            mnSapIf007SDO.setDeliveryPartCode(SapAndCrmFieldDealUtils.generateIdField(mnSapIf007SDO.getDeliveryPartCode()));
            mnSapIf007SDO.setSoldPartCode(SapAndCrmFieldDealUtils.generateIdField(mnSapIf007SDO.getSoldPartCode()));
            //获取明细
            List<MnSapIf007detail> mnSapIf007details = mnSapIf007SDO.getItems();
            //校验明细是否重复
            HashSet mnSapIf007detailSet = new HashSet();
            for (MnSapIf007detail mnSapIf007detail:mnSapIf007details){
                mnSapIf007detailSet.add(mnSapIf007detail.getScItemId());
            }
            if (mnSapIf007details.size()!=mnSapIf007detailSet.size()){
                MnSapCommSDO mnSapCommSDO = new MnSapCommSDO();
                mnSapCommSDO.setHeaderKey(mnSapIf007SDO.getHeaderKey());
                mnSapCommSDO.setStatus(MnSAPStatus.ERROR.getCode());
                mnSapCommSDO.setMessage("调拨预报单明细货品编码不能重复");
                mnSapCommResponse.setData(Lists.newArrayList(mnSapCommSDO));
                saveSapRetry(mnSapIf007Request,"调拨预报单明细货品编码不能重复");
                return mnSapCommResponse;
            }
            /**
             * 如果预报单号和外部行号为空走新增逻辑，如果有外部预报单号没预报单号，根据外部预报单号找预报单号 找到了走新增
             * sapChannel: 90：计划调拨  20：总部销售调拨 （判断是否直发客户（参照售达方、送达方备注）
             * 判断是否工厂直发客户：
             * 1、查收货仓的售达方、送达方编码（对应售达方、送达方不唯一或查不到报错提示）--非直发客户
             *  2、查不到在根据售达方（soldPartCode）和送达方（deliveryPartCode）先找直发客户（对应客户编码、客户地址编码）如果对应上则是直发客户
             *
             * 补充：1、提报组织根据收货仓或客户的销售组织带出
             * 2、分公司客户暂不处理
             */
            /**
             * 一盘货逻辑：
             * F->F1计划调拨预报单明细回传，F->B、F->b销售调拨预报单明细回传，sap都是用007接口；
             * 在一盘货中，如果F->B销售调拨预报单明细且B在试点范围内，则需要创建F->B销售预报单；如果B不在试点范围内，则走老链路创建调拨预报单
             */
            boolean isAddAllocateApplyOrder = false;
            if ("20".equals(mnSapIf007SDO.getSapChannel())) {
               if(!isAllocateApplyOrder(mnSapIf007SDO)){
                   //1、仅传工厂H025，默认成发货仓为武汉1号共享仓
                   //2、传工厂H025、库存地点R010，对应查询的发货仓为武汉1号共享仓
                   //3、除上述两个场景外的其他预报订单均不创建预报订单，提示“不在上线范围内，一盘货应用不进行预报订单的创建”
                   //查询，为空，直接返回错误  H026 RO12
                   Result<DictionarySDO> dictionary = getDefaultStockCode(mnSapIf007SDO.getDeliveryFactoryCode());
                   if(Objects.isNull(dictionary.getResult())){
                       MnSapCommSDO mnSapCommSDO = new MnSapCommSDO();
                       mnSapCommSDO.setHeaderKey(mnSapIf007SDO.getHeaderKey());
                       mnSapCommSDO.setStatus(MnSAPStatus.ERROR.getCode());
                       mnSapCommSDO.setMessage("不在上线范围内，一盘货应用不进行预报订单的创建");
                       mnSapCommResponse.setData(Lists.newArrayList(mnSapCommSDO));
                       return mnSapCommResponse;
                   }

                   setDefaultDeliveryInventoryLocation(mnSapIf007SDO);
                   ForecastOrderBizBatchCreateRequest forecastOrderBizBatchCreateRequest = convertFromMnSapIf007SDO(mnSapIf007SDO);
                   if(StringUtils.isEmpty(mnSapIf007SDO.getDeliveryInventoryLocation())){
                       CreateForecastDTO createForecastDTO = forecastOrderBizBatchCreateRequest.getCreateForecastOrderDTOS().get(0);
                       createForecastDTO.setStockCode(dictionary.getResult().getName());
                   }
                   log.info("mnSapIf007 create forecastOrder param:{}", JSON.toJSONString(forecastOrderBizBatchCreateRequest));
                   Result<ForecastBizAsyncResponse>  createForecastOrderResult = forecastOrderGroupService.batchCreate(forecastOrderBizBatchCreateRequest);
//                        Result<ForecastBizAsyncResponse>  createForecastOrderResult = null;
                   log.info("mnSapIf007 create forecastOrder result:{}", JSON.toJSONString(createForecastOrderResult));
                   MnSapCommSDO mnSapCommSDO = new MnSapCommSDO();
                   mnSapCommSDO.setHeaderKey(mnSapIf007SDO.getHeaderKey());
                   if (createForecastOrderResult.isSuccess()) {
                       mnSapCommSDO.setStatus(MnSAPStatus.SUCCESS.getCode());
                   } else {
                       mnSapCommSDO.setStatus(MnSAPStatus.ERROR.getCode());
                       //todo bz,saveRetry 重试
                       mnSapCommSDO.setMessage("创建中台销售预报单失败");
                   }
                   mnSapCommResponse.setData(Lists.newArrayList(mnSapCommSDO));
                   return mnSapCommResponse;
               }else{
                   //总部销售调拨单 （20下面的，判断是否新增）
                   isAddAllocateApplyOrder = isAddAllocateApplyOrder(mnSapIf007SDO);
                   GetAllocateApplyOrderIdByOutAllocateApplyOrderIdRequest request = new GetAllocateApplyOrderIdByOutAllocateApplyOrderIdRequest();
                   request.setOutAllocateApplyOrderId(mnSapIf007SDO.getOutAllocateApplyOrderId());
                   Result<String> result = allocateApplyOrderReadService.getAllocateApplyOrderIdByOutAllocateApplyOrderId(request);
                   if (Objects.nonNull(result)&&StringUtils.isNotEmpty(result.getResult())){
                       mnSapIf007SDO.setAllocateApplyOrderId(result.getResult());
                   }
               }
            }else{
                //是调拨
                //分新增/非新增
                isAddAllocateApplyOrder = isAddAllocateApplyOrder(mnSapIf007SDO);

                //如果预报单号为空，外部预报单号有值，去库中根据外部预报单号找预报单号，找不到走新增
                if (!isAddAllocateApplyOrder){
                    GetAllocateApplyOrderIdByOutAllocateApplyOrderIdRequest request = new GetAllocateApplyOrderIdByOutAllocateApplyOrderIdRequest();
                    request.setOutAllocateApplyOrderId(mnSapIf007SDO.getOutAllocateApplyOrderId());
                    Result<String> result = allocateApplyOrderReadService.getAllocateApplyOrderIdByOutAllocateApplyOrderId(request);
                    if (Objects.nonNull(result)&&StringUtils.isNotEmpty(result.getResult())){
                        mnSapIf007SDO.setAllocateApplyOrderId(result.getResult());
                    }
                }
            }
            //判断创建什么类型的调拨预报单
            String type = DocumentTypeEnum.PLANNED_ALLOCATION.getCode();
            if ("20".equals(mnSapIf007SDO.getSapChannel())) {
                type = DocumentTypeEnum.HEADQUARTERS_SALES_ALLOCATION.getCode();
            }

            //如果需要校验时间戳
            if (checkTimestamp){
                //时间戳格式校验
                String check = ResponseUtil.check(mnSapIf007SDO.getFeatures());
                if (StringUtils.isNotBlank(check)){
//                saveSapRetry(mnSapIf007Request,check);
                    MnSapCommSDO mnSapCommSDO = new MnSapCommSDO();
                    mnSapCommSDO.setHeaderKey(mnSapIf007SDO.getHeaderKey());
                    mnSapCommSDO.setStatus(MnSAPStatus.ERROR.getCode());
                    mnSapCommSDO.setMessage(check);
                    mnSapCommResponse.setData(Lists.newArrayList(mnSapCommSDO));
                    return mnSapCommResponse;
                }
                //时间戳的判断放在这里 2022.05.24 接口时间戳
                boolean checkModifierTime = checkModifierTime(mnSapIf007SDO);
                //时间校验不通过 放入重试表
                if (!checkModifierTime ){
                    saveSapRetry(mnSapIf007Request,"当前修改时间早于上一次 不允许更新");
                    MnSapCommSDO mnSapCommSDO = new MnSapCommSDO();
                    mnSapCommSDO.setHeaderKey(mnSapIf007SDO.getHeaderKey());
                    mnSapCommSDO.setStatus(MnSAPStatus.ERROR.getCode());
                    mnSapCommSDO.setMessage("当前修改时间早于上一次 不允许更新");
                    mnSapCommResponse.setData(Lists.newArrayList(mnSapCommSDO));
                    saveSapRetry(mnSapIf007Request,"当前修改时间早于上一次 不允许更新");
                    return mnSapCommResponse;
                }else {
                    //校验通过就要放入时间戳
//                    cache(mnSapIf007SDO.getOutAllocateApplyOrderId(),mnSapIf007SDO.getFeatures());
                }
            }
            if (isAddAllocateApplyOrder) {

                //是否工厂直发
                Boolean isDTC =false;
                //提报组织
                String applyOrgId = "";
                String freshApplyOrgId = null;
                //提报组织外部编码 用于工厂直发场景
                String orgOutCode = "";
                //地址编码
                String address = "";
                //收货仓库
                String warehouseId = "";
                if (StringUtils.isEmpty(mnSapIf007SDO.getSapChannel())) {
                    MnSapCommSDO mnSapCommSDO = new MnSapCommSDO();
                    mnSapCommSDO.setHeaderKey(mnSapIf007SDO.getHeaderKey());
                    mnSapCommSDO.setStatus(MnSAPStatus.ERROR.getCode());
                    mnSapCommSDO.setMessage("分销渠道字段不能为空");
                    mnSapCommResponse.setData(Lists.newArrayList(mnSapCommSDO));
                    saveSapRetry(mnSapIf007Request,"分销渠道字段不能为空");
                    return mnSapCommResponse;
                }
                if (StringUtils.isEmpty(mnSapIf007SDO.getSoldPartCode())) {
                    MnSapCommSDO mnSapCommSDO = new MnSapCommSDO();
                    mnSapCommSDO.setHeaderKey(mnSapIf007SDO.getHeaderKey());
                    mnSapCommSDO.setStatus(MnSAPStatus.ERROR.getCode());
                    mnSapCommSDO.setMessage("售达方不能为空");
                    mnSapCommResponse.setData(Lists.newArrayList(mnSapCommSDO));
                    saveSapRetry(mnSapIf007Request,"售达方不能为空");
                    return mnSapCommResponse;
                }
                if (StringUtils.isEmpty(mnSapIf007SDO.getDeliveryPartCode())) {
                    MnSapCommSDO mnSapCommSDO = new MnSapCommSDO();
                    mnSapCommSDO.setHeaderKey(mnSapIf007SDO.getHeaderKey());
                    mnSapCommSDO.setStatus(MnSAPStatus.ERROR.getCode());
                    mnSapCommSDO.setMessage("送达方不能为空");
                    mnSapCommResponse.setData(Lists.newArrayList(mnSapCommSDO));
                    saveSapRetry(mnSapIf007Request,"送达方不能为空");
                    return mnSapCommResponse;
                }
                //类型是90 走计划调拨逻辑 使用总部售达方和总部送达方找仓库，如果是20走销售调拨，先查找地址信息，查不到根据售达方和送达方找仓库信息
                if (DocumentTypeEnum.HEADQUARTERS_SALES_ALLOCATION.getCode().equals(type)){

                    //根据售达方和送达方查找仓库信息，查出多个返回错误，如果有值 取销售组织
                    SearchCargoZoneListRequest searchCargoZoneListRequest = new SearchCargoZoneListRequest();
                    searchCargoZoneListRequest.setSapSaleBPCode(mnSapIf007SDO.getSoldPartCode());
                    //送达方
                    searchCargoZoneListRequest.setSapDeliveryBPCode(mnSapIf007SDO.getDeliveryPartCode());
                    log.info("根据售达方和送达方查找仓库信息入参：售达方："+mnSapIf007SDO.getSoldPartCode()+",送达方："+mnSapIf007SDO.getDeliveryPartCode());
                    SearchCargoZoneListResponse searchCargoZoneListResponse = unifiedInventoryService.searchCargoZoneList(searchCargoZoneListRequest);
                    log.info("根据总部售达方和总部送达方查找仓库信息出参："+ JSONObject.toJSONString(searchCargoZoneListResponse));
                    if (Objects.nonNull(searchCargoZoneListResponse)&&CollectionUtils.isNotEmpty(searchCargoZoneListResponse.getResult())&&searchCargoZoneListResponse.getResult().size()==1) {
                        WarehouseInfo warehouseInfo = searchCargoZoneListResponse.getResult().get(0);
                        warehouseId = warehouseInfo.getId();
                        applyOrgId = warehouseInfo.getSaleOrgId();
                        OrganizationSDO orgSDO = getOrgSDO(applyOrgId);
                        //收货逻辑仓库-》销售组织-〉所属公司
                        if (orgSDO != null && StringUtils.isNotBlank(orgSDO.getParentId())){
                            freshApplyOrgId = orgSDO.getParentId();
                        }

                    } else {
                        if (Objects.nonNull(searchCargoZoneListResponse)&&CollectionUtils.isNotEmpty(searchCargoZoneListResponse.getResult())&&searchCargoZoneListResponse.getResult().size()>1) {
                            MnSapCommSDO mnSapCommSDO = new MnSapCommSDO();
                            mnSapCommSDO.setHeaderKey(mnSapIf007SDO.getHeaderKey());
                            mnSapCommSDO.setStatus(MnSAPStatus.ERROR.getCode());
                            mnSapCommSDO.setMessage("售达方或送达方有误，请重新填写");
                            mnSapCommResponse.setData(Lists.newArrayList(mnSapCommSDO));
                            saveSapRetry(mnSapIf007Request,"售达方或送达方有误，请重新填写");
                            return mnSapCommResponse;
                        }else{
                            //查找客户和客户地址编码
                            BatchQueryAddress2Request batchQueryAddress2Request = new BatchQueryAddress2Request();
                            batchQueryAddress2Request.setAddressCodes(Lists.newArrayList(mnSapIf007SDO.getDeliveryPartCode()));
                            log.info("根据送达方查找客户地址信息入参：送达方："+mnSapIf007SDO.getDeliveryPartCode());
                            BatchQueryAddress2Response batchQueryAddress2Response = otsPlatformEnhanceService.batchQueryAddress2(batchQueryAddress2Request);
                            log.info("根据送达方查找客户地址信息出参："+ JSONObject.toJSONString(batchQueryAddress2Response));
                            if (Objects.nonNull(batchQueryAddress2Response) && CollectionUtils.isNotEmpty(batchQueryAddress2Response.getResult())) {
                                isDTC = true;
                                //根据报文里的soldPartCode 获取到组织架构里的组织id 这个值和组织编号相同
                                orgOutCode = getOrgOutCodeBySoldPartCode(mnSapIf007SDO.getSoldPartCode());
                                address = batchQueryAddress2Response.getResult().get(0).getId();
                                //收货逻辑仓库-》销售组织-〉所属公司
                                if (CollectionUtils.isNotEmpty(batchQueryAddress2Response.getResult())){
                                    CustomerAddressSDO customerAddressSDO = batchQueryAddress2Response.getResult().get(0);
                                    if (customerAddressSDO != null){
                                        String orgBussinessUnitCode = customerAddressSDO.getOrgBussinessUnitCode();
                                        if (StringUtils.isNotBlank(orgBussinessUnitCode)){
                                            freshApplyOrgId = orgBussinessUnitCode;
                                        }
                                    }
                                }
                                //根据报文里的soldPartCode 获取到组织架构里的组织id 这个值和组织编号相同 ,工厂直发的优先取这个值
                                if (StringUtils.isNotBlank(orgOutCode)){
                                    freshApplyOrgId = orgOutCode;
//                                getOrgSDO(orgOutCode)
                                }
                            } else {
                                MnSapCommSDO mnSapCommSDO = new MnSapCommSDO();
                                mnSapCommSDO.setHeaderKey(mnSapIf007SDO.getHeaderKey());
                                mnSapCommSDO.setStatus(MnSAPStatus.ERROR.getCode());
                                mnSapCommSDO.setMessage("售达方或送达方有误，请重新填写");
                                mnSapCommResponse.setData(Lists.newArrayList(mnSapCommSDO));
                                saveSapRetry(mnSapIf007Request,"售达方或送达方有误，请重新填写");
                                return mnSapCommResponse;
                            }
                        }
                    }
                }else{
                    //根据总部售达方和总部送达方查找仓库信息，查出多个或一个都没查到 返回错误，如果有值 取销售组织
                    SearchCargoZoneListRequest searchCargoZoneListRequest = new SearchCargoZoneListRequest();
                    searchCargoZoneListRequest.setSapInternalSalesBPCode(mnSapIf007SDO.getSoldPartCode());
                    //总部送达方
                    searchCargoZoneListRequest.setSapInternalDeliveryBPCode(mnSapIf007SDO.getDeliveryPartCode());
                    log.info("根据总部售达方和总部送达方查找仓库信息入参：总部售达方："+mnSapIf007SDO.getSoldPartCode()+",总部送达方："+mnSapIf007SDO.getDeliveryPartCode());
                    SearchCargoZoneListResponse searchCargoZoneListResponse = unifiedInventoryService.searchCargoZoneList(searchCargoZoneListRequest);
                    log.info("根据总部售达方和总部送达方查找仓库信息出参："+ JSONObject.toJSONString(searchCargoZoneListResponse));
                    if (Objects.nonNull(searchCargoZoneListResponse)&&CollectionUtils.isNotEmpty(searchCargoZoneListResponse.getResult())&&searchCargoZoneListResponse.getResult().size()==1) {
                        WarehouseInfo warehouseInfo = searchCargoZoneListResponse.getResult().get(0);
                        warehouseId = warehouseInfo.getId();
                        orgOutCode = getOrgOutCodeBySoldPartCode(mnSapIf007SDO.getSoldPartCode());
                        OrganizationSDO orgSDO = getOrgSDO(warehouseInfo.getSaleOrgId());
                        //收货逻辑仓库-》销售组织-〉所属公司
                        if (orgSDO != null && StringUtils.isNotBlank(orgSDO.getParentId())){
                            freshApplyOrgId = orgSDO.getParentId();
                        }
                    } else {
                        MnSapCommSDO mnSapCommSDO = new MnSapCommSDO();
                        mnSapCommSDO.setHeaderKey(mnSapIf007SDO.getHeaderKey());
                        mnSapCommSDO.setStatus(MnSAPStatus.ERROR.getCode());
                        mnSapCommSDO.setMessage("售达方或送达方有误，请重新填写");
                        mnSapCommResponse.setData(Lists.newArrayList(mnSapCommSDO));
                        saveSapRetry(mnSapIf007Request,"售达方或送达方有误，请重新填写");
                        return mnSapCommResponse;
                    }
                }

                try {
                    //根据配置表进行数据拦截过滤
                    DataCheckRequest dataCheckRequest = new DataCheckRequest();
                    dataCheckRequest.setOrderType(OrderTypeEnum.APPLYALLOCATE.getCode());
                    dataCheckRequest.setOrgOutCode(getOrgCode(applyOrgId));
                    dataCheckRequest.setVariable(SapAndCrmFieldDealUtils.toDateString(mnSapIf007SDO.getOuterCreateDate()));
                    Result<Boolean> checkResult = interfaceDataSyncConfigQueryService.dataCheck(dataCheckRequest);
                    if (checkResult != null && checkResult.getResult() != null && !checkResult.getResult()){
                        log.info("007.interfaceDataSyncConfigQueryService 拦截 "+JSONObject.toJSONString(mnSapIf007SDO));
                        MnSapCommSDO mnSapCommSDO = new MnSapCommSDO();
                        mnSapCommSDO.setHeaderKey(mnSapIf007SDO.getHeaderKey());
                        mnSapCommSDO.setStatus(MnSAPStatus.SUCCESS.getCode());
                        mnSapCommSDO.setMessage("成功！");
                        mnSapCommResponse.setData(Lists.newArrayList(mnSapCommSDO));
                        return success(mnSapIf007Request);
                    }
                } catch (Throwable e) {
                    log.error("007.interfaceDataSyncConfigQueryService.Error", e);
                }

                //开始组装保存预报单主单数据和明细数据
                AllocateApplyOrderUpdateDTO allocateApplyOrderUpdateDTO = new AllocateApplyOrderUpdateDTO();
                //调拨预报单类型
                allocateApplyOrderUpdateDTO.setType(type);
                //是否工厂直发
                allocateApplyOrderUpdateDTO.setIsDTC(isDTC);
                //提报组织
                if (StringUtils.isNotBlank(freshApplyOrgId)){
                    allocateApplyOrderUpdateDTO.setApplyOrgId(freshApplyOrgId);
                }else{
                    allocateApplyOrderUpdateDTO.setApplyOrgId(StringUtils.isNotBlank(orgOutCode)?orgOutCode:applyOrgId);
                }
                //外部单据号
                allocateApplyOrderUpdateDTO.setOutAllocateApplyOrderId(mnSapIf007SDO.getOutAllocateApplyOrderId());
                //销售组织code
                allocateApplyOrderUpdateDTO.setSaleOrganizationCode(mnSapIf007SDO.getSaleOrganizationCode());
                //部门（产品组）
                allocateApplyOrderUpdateDTO.setGoodsGroup(mnSapIf007SDO.getProductGroupCode());
                //单据日期
                allocateApplyOrderUpdateDTO.setOrderTime(DateFormatUtil.parse(mnSapIf007SDO.getDocTime()));
                //有效起始时间
                allocateApplyOrderUpdateDTO.setTakeEffectTime(DateFormatUtil.parse(mnSapIf007SDO.getBeginTime()));
                //报价有效至
                allocateApplyOrderUpdateDTO.setInvalidDate(DateFormatUtil.parse(mnSapIf007SDO.getEndTime()));
                // 预计交货时间
                allocateApplyOrderUpdateDTO.setHopeDeliveryTime(DateFormatUtil.parse(mnSapIf007SDO.getExpectedDeliveryTime()));
                //客户地址
                if (StringUtils.isNotEmpty(address)) {
                    allocateApplyOrderUpdateDTO.setCustomerAddress(address);
                }
                //总部内部送达方编号 收货仓带出
                allocateApplyOrderUpdateDTO.setSapInternalDeliveryBPCode(mnSapIf007SDO.getDeliveryPartCode());
                //总部内部售达方编号 收货仓带出
                allocateApplyOrderUpdateDTO.setSapInternalSalesBPCode(mnSapIf007SDO.getSoldPartCode());
                //总部渠道编码
                allocateApplyOrderUpdateDTO.setHeadquartersChannelCode(mnSapIf007SDO.getSapChannel());
                //总部组织编码 默认6000
                allocateApplyOrderUpdateDTO.setHeadquartersOrganizationCode("6000");

                //如果没有工厂和库存code 就不找收货单
                if (Objects.nonNull(mnSapIf007SDO.getDeliveryFactoryCode())) {
                    //收货id 根据工厂和库存code查找
                    QueryWarehouseByFactoryCodeAndWarehouseCodeRequest queryWarehouseByFactoryCodeAndWarehouseCodeRequest = new QueryWarehouseByFactoryCodeAndWarehouseCodeRequest();
                    queryWarehouseByFactoryCodeAndWarehouseCodeRequest.setWarehouseCode(mnSapIf007SDO.getDeliveryInventoryLocation());
                    queryWarehouseByFactoryCodeAndWarehouseCodeRequest.setFactoryCode(mnSapIf007SDO.getDeliveryFactoryCode());
                    Result<List<WarehouseInfoDTO>> listResult = forecastWarehouseService.queryWarehouseByFactoryCodeAndWarehouseCode(queryWarehouseByFactoryCodeAndWarehouseCodeRequest);
                    //发货仓库
                    if (Objects.nonNull(listResult)&&CollectionUtils.isNotEmpty(listResult.getResult())){
                        allocateApplyOrderUpdateDTO.setShipWarehouseId(listResult.getResult().get(0).getId());
                    }
                } else {
                    MnSapCommSDO mnSapCommSDO = new MnSapCommSDO();
                    mnSapCommSDO.setHeaderKey(mnSapIf007SDO.getHeaderKey());
                    mnSapCommSDO.setStatus(MnSAPStatus.ERROR.getCode());
                    mnSapCommSDO.setMessage("工厂code不能为空！");
                    mnSapCommResponse.setData(Lists.newArrayList(mnSapCommSDO));
                    saveSapRetry(mnSapIf007Request,"工厂code不能为空！");
                    return mnSapCommResponse;
                }
                //收货仓库
                if (StringUtils.isNotEmpty(warehouseId)){
                    allocateApplyOrderUpdateDTO.setReceiveWarehouseId(Integer.valueOf(warehouseId));
                }
                //装运条件  获取为空
                allocateApplyOrderUpdateDTO.setShipMethod(mnSapIf007SDO.getShipType());
                //备注
                allocateApplyOrderUpdateDTO.setRemark(mnSapIf007SDO.getRemark());
                //明细deliveryInventoryLocation
                List<AllocateApplyOrderDetailCreateDTO> allocateApplyOrderDetails = new ArrayList<>();
                for (MnSapIf007detail mnSapIf007detail : mnSapIf007details) {
                    AllocateApplyOrderDetailCreateDTO allocateApplyOrderDetailCreateDTO = new AllocateApplyOrderDetailCreateDTO();
                    //sap行号
                    allocateApplyOrderDetailCreateDTO.setOutLineNo(mnSapIf007detail.getOutAllocateApplyOrderLineId());
                    //物料编号/货品编码
                    if (Objects.nonNull(mnSapIf007detail.getScItemId())) {
                        String s = mnSapIf007detail.getScItemId();
                        if (s.length()>12){
                            s = s.substring(s.length()-12);
                        }
                        allocateApplyOrderDetailCreateDTO.setScItemId(s);
                    }
                    //数量
                    allocateApplyOrderDetailCreateDTO.setApplyQuantity(Double.valueOf(mnSapIf007detail.getQuantity()).intValue());
                    //销售单位
                    allocateApplyOrderDetailCreateDTO.setUom(mnSapIf007detail.getUnit());
                    //单价
                    if (Objects.nonNull(mnSapIf007detail.getPrice())) {
                        allocateApplyOrderDetailCreateDTO.setUnitPrice(new BigDecimal(mnSapIf007detail.getPrice()));
                    }
                    //折扣后总金额
                    if (Objects.nonNull(mnSapIf007detail.getSubTotalAmount())) {
                        allocateApplyOrderDetailCreateDTO.setSubtotalMoney(new BigDecimal(mnSapIf007detail.getSubTotalAmount()));
                    }
                    //拒绝原因编码
                    allocateApplyOrderDetailCreateDTO.setCloseCode(StringUtils.isNotBlank(mnSapIf007detail.getCloseCode())?mnSapIf007detail.getCloseCode():mnSapIf007detail.getExt());
                    //拒绝原因描述
                    allocateApplyOrderDetailCreateDTO.setCloseReason(StringUtils.isNotBlank(mnSapIf007detail.getCloseReason())?mnSapIf007detail.getCloseReason():mnSapIf007detail.getExt1());
                    allocateApplyOrderDetailCreateDTO.setIsClosed(!org.apache.commons.lang3.StringUtils.isAllBlank(mnSapIf007detail.getExt1(),mnSapIf007detail.getCloseReason()) ? 1 : 0);
//                    allocateApplyOrderDetailCreateDTO.setIsClosed(Objects.nonNull(mnSapIf007detail.getCloseReason()) ? 1 : 0);
                    //行备注
                    allocateApplyOrderDetailCreateDTO.setRemark(mnSapIf007detail.getRemarks());
                    allocateApplyOrderDetails.add(allocateApplyOrderDetailCreateDTO);
                }

                allocateApplyOrderUpdateDTO.setList(allocateApplyOrderDetails);
                allocateApplyOrderUpdateDTO.setOperator(mnSapIf007SDO.getOuterCreator());
                allocateApplyOrderUpdateDTO.setOutModifier(mnSapIf007SDO.getModifier());
                Result<String> result = allocateApplyOrderWriteService.sapCreateAllocateApplyOrder(allocateApplyOrderUpdateDTO);
                if (Objects.isNull(result)||StringUtils.isEmpty(result.getResult())){
                    MnSapCommSDO mnSapCommSDO = new MnSapCommSDO();
                    mnSapCommSDO.setHeaderKey(mnSapIf007SDO.getHeaderKey());
                    mnSapCommSDO.setStatus(MnSAPStatus.ERROR.getCode());
                    mnSapCommSDO.setMessage("调拨预报单创建失败！");
                    mnSapCommResponse.setData(Lists.newArrayList(mnSapCommSDO));
                    saveSapRetry(mnSapIf007Request,"调拨预报单创建失败！");
                    return mnSapCommResponse;
                }
                mnSapIf007SDO.setAllocateApplyOrderId(result.getResult());
            } else {
                //查找预调拨单数据
                QueryAllocateApplyOrderRequest request = new QueryAllocateApplyOrderRequest();
                request.setCode(mnSapIf007SDO.getAllocateApplyOrderId());
                Result<AllocateApplyOrderDetailDTO> allocateApplyOrderDetailDTOResult = allocateApplyOrderReadService.queryAllocateApplyOrderByCode(request);
                if (Objects.isNull(allocateApplyOrderDetailDTOResult) || Objects.isNull(allocateApplyOrderDetailDTOResult.getResult())) {
                    MnSapCommSDO mnSapCommSDO = new MnSapCommSDO();
                    mnSapCommSDO.setHeaderKey(mnSapIf007SDO.getHeaderKey());
                    mnSapCommSDO.setStatus(MnSAPStatus.ERROR.getCode());
                    mnSapCommSDO.setMessage("预报单号查不到数据");
                    mnSapCommResponse.setData(Lists.newArrayList(mnSapCommSDO));
                    saveSapRetry(mnSapIf007Request,"预报单号查不到数据");
                    return mnSapCommResponse;
                }
                AllocateApplyOrderDetailDTO allocateApplyOrderDetailDTO = allocateApplyOrderDetailDTOResult.getResult();
                //类型不一致不准修改
                if (!type.equals(allocateApplyOrderDetailDTO.getType())){
                    MnSapCommSDO mnSapCommSDO = new MnSapCommSDO();
                    mnSapCommSDO.setHeaderKey(mnSapIf007SDO.getHeaderKey());
                    mnSapCommSDO.setStatus(MnSAPStatus.ERROR.getCode());
                    mnSapCommSDO.setMessage("修改调拨预报单时不能修改调拨预报单类型！");
                    mnSapCommResponse.setData(Lists.newArrayList(mnSapCommSDO));
                    saveSapRetry(mnSapIf007Request,"修改调拨预报单时不能修改调拨预报单类型！");
                    return mnSapCommResponse;
                }

                AllocateApplyOrderUpdateDTO allocateApplyOrderUpdateDTO = new AllocateApplyOrderUpdateDTO();
                allocateApplyOrderUpdateDTO.setId(allocateApplyOrderDetailDTO.getId());
                //预报单号
                allocateApplyOrderUpdateDTO.setCode(mnSapIf007SDO.getAllocateApplyOrderId());
                //外部单据号
                allocateApplyOrderUpdateDTO.setOutAllocateApplyOrderId(mnSapIf007SDO.getOutAllocateApplyOrderId());
                //报价单类型 平台无这字段
//        销售组织code
//        allocateApplyOrderUpdateDTO.setSaleOrganizationCode(mnSapIf007SDO.getSaleOrganizationCode());
//        //分销渠道
//        allocateApplyOrderUpdateDTO.setHeadquartersChannelCode(mnSapIf007SDO.getSapChannel());
//        //部门（产品组）
//        allocateApplyOrderUpdateDTO.setGoodsGroup(mnSapIf007SDO.getProductGroupCode());
//        //销售办公室 销售渠道
//        allocateApplyOrderUpdateDTO.setSaleChannel(mnSapIf007SDO.getSapChannel());
//        //销售部门code
//        allocateApplyOrderUpdateDTO.setSaleDepartmentCode(mnSapIf007SDO.getSaleDepartmentCode());
//        //更改人mnSapIf007SDO.getModifier()
//        allocateApplyOrderUpdateDTO.setUpdater("1234");
//        //更改日期mnSapIf007SDO.getModifyTime()
//        allocateApplyOrderUpdateDTO.setGmtModified(new Date());
//        //单据日期
                allocateApplyOrderUpdateDTO.setOrderTime(DateFormatUtil.parse(mnSapIf007SDO.getDocTime()));
                //有效起始时间
                allocateApplyOrderUpdateDTO.setTakeEffectTime(DateFormatUtil.parse(mnSapIf007SDO.getBeginTime()));
                //报价有效至
                allocateApplyOrderUpdateDTO.setInvalidDate(DateFormatUtil.parse(mnSapIf007SDO.getEndTime()));
                // 预计交货时间
                allocateApplyOrderUpdateDTO.setHopeDeliveryTime(DateFormatUtil.parse(mnSapIf007SDO.getExpectedDeliveryTime()));
                //如果没有工厂和库存code 就不找收货单
//        if (Objects.nonNull(mnSapIf007SDO.getDeliveryInventoryLocation())&&Objects.nonNull(mnSapIf007SDO.getDeliveryFactoryCode())){

                //提报组织
                String applyOrgId = "";
                if (Objects.nonNull(mnSapIf007SDO.getDeliveryFactoryCode())) {
                    //收货id 根据工厂和库存code查找
                    QueryWarehouseByFactoryCodeAndWarehouseCodeRequest queryWarehouseByFactoryCodeAndWarehouseCodeRequest = new QueryWarehouseByFactoryCodeAndWarehouseCodeRequest();
                    queryWarehouseByFactoryCodeAndWarehouseCodeRequest.setWarehouseCode(mnSapIf007SDO.getDeliveryInventoryLocation());
                    queryWarehouseByFactoryCodeAndWarehouseCodeRequest.setFactoryCode(mnSapIf007SDO.getDeliveryFactoryCode());
                    Result<List<WarehouseInfoDTO>> listResult = forecastWarehouseService.queryWarehouseByFactoryCodeAndWarehouseCode(queryWarehouseByFactoryCodeAndWarehouseCodeRequest);
                    //发货仓库
                    if (Objects.nonNull(listResult)&&CollectionUtils.isNotEmpty(listResult.getResult())){
                        allocateApplyOrderUpdateDTO.setShipWarehouseId(listResult.getResult().get(0).getId());
                        applyOrgId = listResult.getResult().get(0).getSaleOrgId();
                    }
                }

                try {
                    //根据配置表进行数据拦截过滤
                    DataCheckRequest dataCheckRequest = new DataCheckRequest();
                    dataCheckRequest.setOrderType(OrderTypeEnum.APPLYALLOCATE.getCode());
                    dataCheckRequest.setOrgOutCode(getOrgCode(applyOrgId));
                    dataCheckRequest.setVariable(SapAndCrmFieldDealUtils.toDateString(mnSapIf007SDO.getOuterCreateDate()));
                    Result<Boolean> checkResult = interfaceDataSyncConfigQueryService.dataCheck(dataCheckRequest);
                    if (checkResult != null && checkResult.getResult() != null && !checkResult.getResult()){
                        log.info("007.interfaceDataSyncConfigQueryService 拦截 "+JSONObject.toJSONString(mnSapIf007SDO));
                        MnSapCommSDO mnSapCommSDO = new MnSapCommSDO();
                        mnSapCommSDO.setHeaderKey(mnSapIf007SDO.getHeaderKey());
                        mnSapCommSDO.setStatus(MnSAPStatus.SUCCESS.getCode());
                        mnSapCommSDO.setMessage("成功！");
                        mnSapCommResponse.setData(Lists.newArrayList(mnSapCommSDO));
                        return success(mnSapIf007Request);
                    }
                } catch (Throwable e) {
                    log.error("007.interfaceDataSyncConfigQueryService.Error", e);
                }

                //装运条件  获取为空
                allocateApplyOrderUpdateDTO.setShipMethod(mnSapIf007SDO.getShipType());
                //备注
                allocateApplyOrderUpdateDTO.setRemark(mnSapIf007SDO.getRemark());
                //售达方
//        allocateApplyOrderUpdateDTO.setSapSalesBPCode(mnSapIf007SDO.getSoldPartCode());
//        //送达方
//        allocateApplyOrderUpdateDTO.setSapDeliveryBPCode(mnSapIf007SDO.getDeliveryPartCode());
                //扩展信息
//        allocateApplyOrderUpdateDTO.set(null,mnSapIf007SDO.getFeatures());
                //文档中没这个字段
//        allocateApplyOrderUpdateDTO.set(null,mnSapIf007SDO.getExt());
                //明细deliveryInventoryLocation
                List<AllocateApplyOrderDetailCreateDTO> allocateApplyOrderDetails = new ArrayList<>();
                for (MnSapIf007detail mnSapIf007detail : mnSapIf007details) {
                    AllocateApplyOrderDetailCreateDTO allocateApplyOrderDetailCreateDTO = new AllocateApplyOrderDetailCreateDTO();
                    //预调拨单id
                    allocateApplyOrderDetailCreateDTO.setAllocateApplyOrderId(Integer.valueOf(allocateApplyOrderDetailDTO.getId().toString()));
//            //行号
//            if (Objects.isNull(mnSapIf007detail.getAllocateApplyOrderLineId())){
//                allocateApplyOrderDetailCreateDTO.setLineNo(Integer.valueOf(mnSapIf007detail.getAllocateApplyOrderLineId()));
//            }
//            //sap行号
                    allocateApplyOrderDetailCreateDTO.setOutLineNo(mnSapIf007detail.getOutAllocateApplyOrderLineId());
//            //物料编号/货品编码
                    if (Objects.nonNull(mnSapIf007detail.getScItemId())) {
                        String s = mnSapIf007detail.getScItemId();
                        if (s.length()>12){
                            s = s.substring(s.length()-12);
                        }
                        allocateApplyOrderDetailCreateDTO.setScItemId(s);
                    }
//            //数量
                    allocateApplyOrderDetailCreateDTO.setApplyQuantity(Double.valueOf(mnSapIf007detail.getQuantity()).intValue());
//            //销售单位
                    allocateApplyOrderDetailCreateDTO.setUom(mnSapIf007detail.getUnit());
//            //单价
                    if (Objects.nonNull(mnSapIf007detail.getPrice())) {
                        allocateApplyOrderDetailCreateDTO.setUnitPrice(new BigDecimal(mnSapIf007detail.getPrice()));
                    }
//            //折扣后总金额
                    if (Objects.nonNull(mnSapIf007detail.getSubTotalAmount())) {
                        allocateApplyOrderDetailCreateDTO.setSubtotalMoney(new BigDecimal(mnSapIf007detail.getSubTotalAmount()));
                    }
//            //拒绝原因编码
                    allocateApplyOrderDetailCreateDTO.setCloseCode(StringUtils.isNotBlank(mnSapIf007detail.getCloseCode())?mnSapIf007detail.getCloseCode():mnSapIf007detail.getExt());
//            //拒绝原因描述
                    allocateApplyOrderDetailCreateDTO.setCloseReason(StringUtils.isNotBlank(mnSapIf007detail.getCloseReason())?mnSapIf007detail.getCloseReason():mnSapIf007detail.getExt1());
                    allocateApplyOrderDetailCreateDTO.setIsClosed(!org.apache.commons.lang3.StringUtils.isAllBlank(mnSapIf007detail.getCloseReason(),mnSapIf007detail.getExt1()) ? 1 : 0);
//                    allocateApplyOrderDetailCreateDTO.setIsClosed(Objects.nonNull(mnSapIf007detail.getCloseReason()) ? 1 : 0);
//            //行备注
                    allocateApplyOrderDetailCreateDTO.setRemark(mnSapIf007detail.getRemarks());
                    //扩展信息
//            allocateApplyOrderDetail.setFeatures(null,mnSapIf007detail.getFeatures());
                    allocateApplyOrderDetails.add(allocateApplyOrderDetailCreateDTO);
                }

                allocateApplyOrderUpdateDTO.setList(allocateApplyOrderDetails);
                //操作人
                allocateApplyOrderUpdateDTO.setOperator(mnSapIf007SDO.getOuterCreator());
                allocateApplyOrderUpdateDTO.setOutModifier(mnSapIf007SDO.getModifier());
                //更新预调拨单数据
                Result<Boolean> updateAllocateApplyOrder = allocateApplyOrderWriteService.sapUpdateAllocateApplyOrder(allocateApplyOrderUpdateDTO);
                if (Objects.isNull(updateAllocateApplyOrder)) {
                    MnSapCommSDO mnSapCommSDO = new MnSapCommSDO();
                    mnSapCommSDO.setHeaderKey(mnSapIf007SDO.getHeaderKey());
                    mnSapCommSDO.setStatus(MnSAPStatus.ERROR.getCode());
                    mnSapCommSDO.setMessage("更新预报单失败，返回值为空！");
                    saveSapRetry(mnSapIf007Request,"更新预报单失败，返回值为空！");
                    mnSapCommResponse.setData(Lists.newArrayList(mnSapCommSDO));
                    return mnSapCommResponse;
                }
                if (Objects.isNull(updateAllocateApplyOrder.getResult())||!updateAllocateApplyOrder.getResult()) {
                    MnSapCommSDO mnSapCommSDO = new MnSapCommSDO();
                    mnSapCommSDO.setHeaderKey(mnSapIf007SDO.getHeaderKey());
                    mnSapCommSDO.setStatus(MnSAPStatus.ERROR.getCode());
                    mnSapCommSDO.setMessage("更新预报单失败");
                    mnSapCommResponse.setData(Lists.newArrayList(mnSapCommSDO));
                    saveSapRetry(mnSapIf007Request,"更新预报单失败");
                    return mnSapCommResponse;
                }
            }
            //判断返回值是成功还是失败，失败给提示。
            //@TODO 这个字段有问题 后面改
            MnSapCommSDO mnSapCommSDO = new MnSapCommSDO();
            mnSapCommSDO.setHeaderKey(mnSapIf007SDO.getHeaderKey());
            mnSapCommSDO.setStatus(MnSAPStatus.SUCCESS.getCode());
            mnSapCommSDO.setExtId(mnSapIf007SDO.getAllocateApplyOrderId());
            List<MnSapCommDetail> mnSapCommDetails = new ArrayList<>();
            for (MnSapIf007detail mnSapIf007detail : mnSapIf007details) {
                MnSapCommDetail mnSapCommDetail = new MnSapCommDetail();
                mnSapCommDetail.setItemKey(mnSapIf007detail.getItem_key());
                mnSapCommDetail.setStatus(MnSAPStatus.SUCCESS.getCode());
                mnSapCommDetails.add(mnSapCommDetail);
            }
            mnSapCommSDO.setItem(mnSapCommDetails);
            mnSapCommResponse.setData(Lists.newArrayList(mnSapCommSDO));
            //如果校验时间戳戳 这里记录时间戳
            if (checkTimestamp){
                cache(mnSapIf007SDO.getOutAllocateApplyOrderId(),mnSapIf007SDO.getFeatures());
            }
            return mnSapCommResponse;
        } catch (Exception e) {
            log.error("007.externalSyncUpdateAllocateApplyOrder.error,requeset:{}, Exception:{}", JSONObject.toJSONString(mnSapIf007Request), e);
            MnSapCommSDO mnSapCommSDO = new MnSapCommSDO();
            mnSapCommSDO.setHeaderKey(mnSapIf007SDO.getHeaderKey());
            mnSapCommSDO.setStatus(MnSAPStatus.ERROR.getCode());
            mnSapCommSDO.setMessage("007接口同步失败");
            mnSapCommResponse.setData(Lists.newArrayList(mnSapCommSDO));
            saveSapRetry(mnSapIf007Request,"007接口同步失败");
            return success(mnSapIf007Request);
        }
    }

    private void setDefaultDeliveryInventoryLocation(MnSapIf007SDO mnSapIf007SDO) {

        if(StringUtils.isNotBlank(mnSapIf007SDO.getDeliveryInventoryLocation())){
            return;
        }
        if ("H025".equals(mnSapIf007SDO.getDeliveryFactoryCode())){
            mnSapIf007SDO.setDeliveryInventoryLocation("R010");
        }else{
            mnSapIf007SDO.setDeliveryInventoryLocation("DEFAULT");
        }
    }

    //判断是否是预报调拨单
    private boolean isAllocateApplyOrder(MnSapIf007SDO mnSapIf007SDO){
        if (StringUtils.isNotEmpty(mnSapIf007SDO.getAllocateApplyOrderId())){
            return true;
        }
        return false;
    }
    //是否是新增（SAP过来中来没有则需要新增，中台有则需要更新）
    private boolean isAddAllocateApplyOrder(MnSapIf007SDO mnSapIf007SDO){
        if (StringUtils.isEmpty(mnSapIf007SDO.getAllocateApplyOrderId())&&StringUtils.isEmpty(mnSapIf007SDO.getOutAllocateApplyOrderId())){
            return  true;
        }
        return false;
    }

    private String formatSapHead(String param) {
        return param.trim().replaceFirst("^0+","");
    }

    /**
     * 参数转换，转换成预报单参数
     * @param mnSapIf007SDO
     * @return
     */
    private ForecastOrderBizBatchCreateRequest convertFromMnSapIf007SDO(MnSapIf007SDO mnSapIf007SDO) {
        ForecastOrderBizBatchCreateRequest result = new ForecastOrderBizBatchCreateRequest();
        result.setReqNo(UUIDUtil.newWithoutMinus());
        //todo bz，联调阶段，fromSys、businessType先写死，以后要查客户中心
        result.setFromSys("APP_SAP");//
        result.setBusinessType("11");//
        // 判断业务单元编码
        QueryCustomerResponseDTO dto = determineBusinessUnitCode(mnSapIf007SDO);
        result.setBusinessUnitCode(dto.getBusinessUnitCode());
        CreateForecastDTO createForecastDTO = new CreateForecastDTO();
        createForecastDTO.setOrderCategoryCode(OrderCategoryEnum.GROUP.getCode());
        createForecastDTO.setOrderChannelCode(OrderChannelEnum.SEPARATE_WAREHOUSE.getCode());
        createForecastDTO.setSourceOrderNo(formatSapHead(mnSapIf007SDO.getOutAllocateApplyOrderId()));
        createForecastDTO.setOuterOrderId(formatSapHead(mnSapIf007SDO.getOutAllocateApplyOrderId()));
        createForecastDTO.setSalesOrderType(mnSapIf007SDO.getOrderType());
        createForecastDTO.setDeliveryMethodCode(mnSapIf007SDO.getShipType());
        createForecastDTO.setExpectedDeliveryDate(TimeUtil.formatYYYY_MM_dd(TimeUtil.parseSimpleDateFormat(mnSapIf007SDO.getExpectedDeliveryTime())));
        createForecastDTO.setDeliveryFactoryCode(mnSapIf007SDO.getDeliveryFactoryCode());
        createForecastDTO.setStockCode(mnSapIf007SDO.getDeliveryInventoryLocation());
        //todo bz,确认对应关系是否正确
        createForecastDTO.setShipToPartyCode(mnSapIf007SDO.getDeliveryPartCode());
        //todo bz， 客户编码
        createForecastDTO.setCustomerCode(mnSapIf007SDO.getSoldPartCode());
        createForecastDTO.setProductGroupCode(mnSapIf007SDO.getProductGroupCode());
        //todo bz， 渠道对应关系是否正确
        createForecastDTO.setBusinessChannel(mnSapIf007SDO.getSapChannel());
        createForecastDTO.setSalesChannelCode(mnSapIf007SDO.getSaleChannel());
        setName(mnSapIf007SDO,createForecastDTO);
        createForecastDTO.setCustomerGrade(dto.getCustomerLevel());
        log.info("convertFromMnSapIf007SDO createForecastDTO = {}",JSON.toJSONString(createForecastDTO));

        createForecastDTO.setSalesDepartmentCode(mnSapIf007SDO.getSaleDepartmentCode());
        createForecastDTO.setSalesOrganizationCode(mnSapIf007SDO.getSaleOrganizationCode());
        Date beginTime = DateUtils.string2Date(mnSapIf007SDO.getBeginTime());
        createForecastDTO.setValidBeginDate(DateUtils.formatDate(beginTime));
        Date endTime = DateUtils.string2Date(mnSapIf007SDO.getEndTime());
        createForecastDTO.setValidEndTime(DateUtils.formatDate(endTime)+" 23:59:59");
        //todo bz，单据原因编码
//        createForecastDTO.setOrderReasonCode(mnSapIf007SDO.get);
        //todo bz，发货仓库编码
//        createForecastDTO.setShippingWarehouseCode(mnSapIf007SDO.get);
        createForecastDTO.setDeliveryFactoryCode(mnSapIf007SDO.getDeliveryFactoryCode());
        if(StringUtils.isNotBlank(mnSapIf007SDO.getDeliveryInventoryLocation())){
            createForecastDTO.setStockCode(mnSapIf007SDO.getDeliveryInventoryLocation());
        }
        //todo bz，收货仓库编码
//        createForecastDTO.setReceiveWarehouseCode();
//        createForecastDTO.setReceiveFactoryCode();
//        createForecastDTO.setReceiveStockCode();
        //todo bz， 对应关系是否正确
        createForecastDTO.setNote(mnSapIf007SDO.getRemark());
        createForecastDTO.setCreatorCode(mnSapIf007SDO.getOuterCreator());
//        createForecastDTO.setSubmitFlag();
//        createForecastDTO.setFulfillmentTypeCode();
//        createForecastDTO.setAutoFulfillment();
//        createForecastDTO.setSourceOrderDate();
        List<CreateForecastDetailDTO> forecastOrderDetailDTOS = mnSapIf007SDO.getItems().stream().map(detail -> convertFromMnSapIf007detail(detail, mnSapIf007SDO.getDeliveryFactoryCode(), mnSapIf007SDO.getDeliveryInventoryLocation())).collect(Collectors.toList());
        createForecastDTO.setForecastOrderDetailDTOS(forecastOrderDetailDTOS);
        if ("X".equals(mnSapIf007SDO.getExt())) {
            // 奶卡订单标
            JSONObject json = new JSONObject();
            json.put("mikeCardFlag", "true");
            createForecastDTO.setBizFeatures(json.toJSONString());
            if (createForecastDTO.getOrderBizTag() == null) {
                createForecastDTO.setOrderBizTag(Lists.newArrayList("milk_card"));
            } else {
                createForecastDTO.getOrderBizTag().add("milk_card");
            }
        }
        String bizFeatures = createForecastDTO.getBizFeatures();
        JSONObject exist = null;
        if (StringUtils.isNotBlank(bizFeatures)){
             exist = JSON.parseObject(bizFeatures);
        }else{
            exist = new JSONObject();
        }
        exist.put("validEndTime",createForecastDTO.getValidEndTime());
        createForecastDTO.setBizFeatures(exist.toJSONString());
//        createForecastDTO.setBizFeatures(mnSapIf007SDO.getFeatures());
        result.setCreateForecastOrderDTOS(Lists.newArrayList(createForecastDTO));
        return result;
    }

//    private void setStockCode(CreateForecastDTO createForecastDTO) {
//        Result<DictionarySDO> dictionary = getDictionary(createForecastDTO.getDeliveryFactoryCode());
//        if(Objects.isNull(dictionary.getResult())){
//           return;
//        }
//        DictionarySDO result = dictionary.getResult();
//        String name = result.getName();
//        createForecastDTO.setStockCode(name);
//    }
    private  Result<DictionarySDO> getDefaultStockCode(String dictCode){
        log.info("MnSapIf007V2ServiceImpl getDefaultStockCode dictCode={}",dictCode);
        QueryDictionaryRequest queryDictionaryRequest = new QueryDictionaryRequest();
        queryDictionaryRequest.setDictCode(dictCode);
        queryDictionaryRequest.setGroupCode(DEFAULT_INVENTORY_LOCATION);
        Result<DictionarySDO> dictionarySDOResult = dictionaryQueryService.querySingle(queryDictionaryRequest);
        log.info("MnSapIf007V2ServiceImpl setStockCode dictionarySDOResult ={}",JSON.toJSONString(dictionarySDOResult));
        return dictionarySDOResult;
    }


    /**
     * 判定业务单元编码
     *
     * @param mnSapIf007SDO
     * @return
     */
    private QueryCustomerResponseDTO determineBusinessUnitCode(MnSapIf007SDO mnSapIf007SDO) {
        QueryCustomerResponseDTO dto = new QueryCustomerResponseDTO();
        // 销售组织
        String salesOrgCode = mnSapIf007SDO.getSaleOrganizationCode();
        // 业务渠道
        String sapChannel = mnSapIf007SDO.getSapChannel();
        // 产品组
        String productGroup = mnSapIf007SDO.getProductGroupCode();
        // 售达方
        String soldPartCode = mnSapIf007SDO.getSoldPartCode();
        // 客户组
        String customerGroup = null;
        String customerLevel = null;
        QueryCustomerRequest customerRequest = new QueryCustomerRequest();
        try {
            if (StringUtils.isNotBlank(salesOrgCode) && StringUtils.isNotBlank(sapChannel)
                && StringUtils.isNotBlank(productGroup) && StringUtils.isNotBlank(soldPartCode)) {
                customerRequest.setSalesOrganizationCode(salesOrgCode);
                customerRequest.setSalesChannelCode(sapChannel);
                customerRequest.setBusinessTypes(Lists.newArrayList(productGroup));
                customerRequest.setSoldToPartyCode(soldPartCode);
                customerRequest.setSize(1);
                QueryCustomerResponse customerResponse = otsApplicationAdapterSdkService.queryCustomer(customerRequest);
                log.info("007查询客户 request={}，response={}", JSON.toJSONString(customerRequest), JSON.toJSONString(customerResponse));
                if (customerResponse != null && CollectionUtils.isNotEmpty(customerResponse.getItems())) {
                    if (customerResponse.getTotal() == 1) {
                        JSONObject json = JSON.parseObject(JSON.toJSONString(customerResponse.getItems().get(0)));
                        customerGroup = json != null ? json.getString("customerGroupCode") : null;
                        customerLevel = json != null ? json.getString("customerLevel") : null;
                    }
                }
            }
        } catch (Exception e) {
            log.error("查询客户组异常,customerRequest=" + JSON.toJSONString(customerRequest), e);
        }

        // 根据客户信息获取业务单元
        GetBusinessUnitSalesRequest unitSalesRequest = new GetBusinessUnitSalesRequest();
        unitSalesRequest.setSalesOrganizationCode(salesOrgCode);
        unitSalesRequest.setBusinessChannelCode(sapChannel);
        unitSalesRequest.setSoldToPartyCode(soldPartCode);
        unitSalesRequest.setCustomerGroup(customerGroup);
        unitSalesRequest.setWarehouseCode(getWarehouseCode(mnSapIf007SDO));
        log.info("MnSapIf007V2ServiceImpl getBusinessUnitSales request={}", JSON.toJSONString(unitSalesRequest));
        Result<String> result = otsApplicationAdapterSdkService.getBusinessUnitSales(unitSalesRequest);
        log.info("MnSapIf007V2ServiceImpl getBusinessUnitSales result={}", JSON.toJSONString(result));
        String businessUnitCode = null;
        if (Objects.nonNull(result) && org.apache.commons.lang3.StringUtils.isNotBlank(result.getResult())) {
            businessUnitCode = result.getResult();
        }else {
            businessUnitCode = salesOrgCode;
        }
//        String businessUnitCode = BusinessUnitEnum.matchBusinessUnit(salesOrgCode, sapChannel, customerGroup).getCode();
//        log.info("判断业务单元salesOrgCode={}，sapChannel={}，customerGroup={}，businessUnitCode={}", salesOrgCode, sapChannel,
//            customerGroup, businessUnitCode);
        dto.setCustomerLevel(customerLevel);
        dto.setBusinessUnitCode(businessUnitCode);
        return dto;
    }
    private String getWarehouseCode(MnSapIf007SDO mnSapIf007SDO){
        String warehouseCode = null;
        try {
            QueryWarehouseByFactoryCodeAndWarehouseCodeRequest queryWarehouseByFactoryCodeAndWarehouseCodeRequest = new QueryWarehouseByFactoryCodeAndWarehouseCodeRequest();
            queryWarehouseByFactoryCodeAndWarehouseCodeRequest.setWarehouseCode(mnSapIf007SDO.getDeliveryInventoryLocation());
            queryWarehouseByFactoryCodeAndWarehouseCodeRequest.setFactoryCode(mnSapIf007SDO.getDeliveryFactoryCode());
            log.info("MnSapIf007V2ServiceImpl  queryWarehouseByFactoryCodeAndWarehouseCode request={}", JSON.toJSONString(queryWarehouseByFactoryCodeAndWarehouseCodeRequest));
            Result<List<WarehouseInfoDTO>> listResult = forecastWarehouseService.queryWarehouseByFactoryCodeAndWarehouseCode(queryWarehouseByFactoryCodeAndWarehouseCodeRequest);
            log.info("MnSapIf007V2ServiceImpl  queryWarehouseByFactoryCodeAndWarehouseCode result={}", JSON.toJSONString(listResult));
            //发货仓库
            if (Objects.nonNull(listResult)&&CollectionUtils.isNotEmpty(listResult.getResult())){
                warehouseCode = listResult.getResult().get(0).getWarehouseCode();
            }
        }catch (Exception e){
            log.error("MnSapIf007V2ServiceImpl getWarehouseCode error ",e);
        }

        return "default".equalsIgnoreCase(warehouseCode)? null:warehouseCode;
    }
    private CreateForecastDetailDTO convertFromMnSapIf007detail(MnSapIf007detail mnSapIf007detail, String deliveryFactoryCode, String deliveryInventoryLocation) {
        CreateForecastDetailDTO createForecastDetailDTO = new CreateForecastDetailDTO();
        createForecastDetailDTO.setProductCode(formatSapHead(mnSapIf007detail.getScItemId()));
        createForecastDetailDTO.setProductQuantity(mnSapIf007detail.getQuantity().replaceAll("\\..*", "").trim());
        createForecastDetailDTO.setSaleUnitCode(mnSapIf007detail.getUnit());
        createForecastDetailDTO.setNote(mnSapIf007detail.getRemarks());
        //todo bz ,
//        createForecastDetailDTO.setDeliveryFactoryCode(mnSapIf007detail.);
        createForecastDetailDTO.setSourceLineNum(formatSapHead(mnSapIf007detail.getOutAllocateApplyOrderLineId()));
        createForecastDetailDTO.setOuterLineId(formatSapHead(mnSapIf007detail.getOutAllocateApplyOrderLineId()));
        createForecastDetailDTO.setDeliveryFactoryCode(deliveryFactoryCode);
        createForecastDetailDTO.setStockCode(deliveryInventoryLocation);
        //todo bz ,allocateApplyOrderLineId 物料行id ,咋传
//        createForecastDetailDTO.setProductCode(mnSapIf007detail.);
//        createForecastDetailDTO.setUnitPrice(mnSapIf007detail.getPrice());
//        createForecastDetailDTO.setDiscountAmount(mnSapIf007detail.getSubTotalAmount());
//        createForecastDetailDTO.setBizFeatures(mnSapIf007detail.getFeatures());
        return createForecastDetailDTO;

    }

    public  String getOrgCode(String orgId){
        //发货收货仓的组织id name
        BaselineGetOrganizationByIdsRequest r = new BaselineGetOrganizationByIdsRequest();
        if (org.apache.commons.lang3.StringUtils.isNotBlank(orgId)){
            r.setIds(Lists.newArrayList(orgId));
            Object obj = baseDataService.baselineGetOrganizationByIds(r);
            JSONObject o = JSONObject.parseObject(JSONObject.toJSONString(obj));
            if (o != null){
                JSONArray array = o.getJSONArray("result");
                if (array != null && array.size() > 0){
                    JSONObject j = array.getJSONObject(0).getJSONObject("organizationSDO");
                    if (j != null){
                        return j.getString("code");
                    }
                }
            }
        }
        return null;
    }
    public  String getOrgOutCodeBySoldPartCode(String soldPartCode){
        if (StringUtils.isBlank(soldPartCode)){
            return null;
        }
        BaselineGetOrganizationByCodes2Request baselineGetOrganizationByCodes2Request = new BaselineGetOrganizationByCodes2Request();
        baselineGetOrganizationByCodes2Request.setIds(Lists.newArrayList(soldPartCode));
        BaselineGetOrganizationByCodes2Response baselineGetOrganizationByCodes2Response = baseDataService.baselineGetOrganizationByCodes2(baselineGetOrganizationByCodes2Request);
        if (Objects.nonNull(baselineGetOrganizationByCodes2Response)&&CollectionUtils.isNotEmpty(baselineGetOrganizationByCodes2Response.getResult())){
            String outcode = baselineGetOrganizationByCodes2Response.getResult().get(0).getId();
            if (StringUtils.isNotBlank(outcode)){
                return outcode;
            }
        }
        return "6000";
    }


    public static MnSapCommResponse success(MnSapIf007Request request){
        MnSapCommResponse response = new MnSapCommResponse();
        MessageHeaderSDO messageHeaderSDO = request.getMessageHeader();
        if (request.getData() != null){
            List<MnSapCommSDO> mnSapCommSDOS = Lists.newArrayList();
            MnSapCommSDO mnSapCommSDO = new MnSapCommSDO();
            MnSapIf007SDO mnSapIf007SDO = request.getData();
            mnSapCommSDO.setHeaderKey(mnSapIf007SDO.getHeaderKey());
            mnSapCommSDO.setExtId(null);
            mnSapCommSDO.setMessage(MnSAPStatus.SUCCESS.getMsg());
            mnSapCommSDO.setStatus(MnSAPStatus.SUCCESS.getCode());
            List<MnSapCommDetail> mnSapCommDetails = Lists.newArrayList();
            if (CollectionUtils.isNotEmpty(mnSapIf007SDO.getItems())) {
                mnSapCommDetails = mnSapIf007SDO.getItems().stream().map(m -> {
                    MnSapCommDetail mnSapCommDetail = new MnSapCommDetail();
                    mnSapCommDetail.setItemKey(m.getItem_key());
                    mnSapCommDetail.setStatus(MnSAPStatus.SUCCESS.getCode());
                    mnSapCommDetail.setMessage(MnSAPStatus.SUCCESS.getMsg());
                    return mnSapCommDetail;
                }).collect(Collectors.toList());
                mnSapCommSDO.setItem(mnSapCommDetails);
            }
            mnSapCommSDOS.add(mnSapCommSDO);
            response.setData(mnSapCommSDOS);
        }
        if (Objects.nonNull(messageHeaderSDO)) {
            response.setInterfacePath(messageHeaderSDO.getInterfacePath());
            response.setMessageId(messageHeaderSDO.getMessageId());
        }
        return response;
    }

    OrganizationSDO getOrgSDO(String orgId){
        if (StringUtils.isBlank(orgId)){
            return null;
        }
//        GetOrganiztionByIdRequest getOrganiztionByIdRequest = new GetOrganiztionByIdRequest();
//        getOrganiztionByIdRequest.setId(orgId);
//        OrganizationSDO organiztionById = otsPlatformEnhanceService.getOrganiztionById(getOrganiztionByIdRequest);
        BaselineGetOrganizationById2Request request = new BaselineGetOrganizationById2Request();
        request.setId(orgId);
        Result<OrganizationSDO> organizationSDOResult = baseDataService.baselineGetOrganizationById2(request);
        if (organizationSDOResult != null){
            return organizationSDOResult.getResult();
        }
        return null;
    }
    /**
     * 保存sap重试记录
     *
     */
    public void saveSapRetry(MnSapIf007Request request, String message){
        try{
            if (request == null || org.apache.commons.lang3.StringUtils.isBlank(message)){
                return;
            }
            MnSapIf007SDO sdo = request.getData();
            SapRetrySaveRequest sapRetrySaveRequest = new SapRetrySaveRequest();
            String requestJson = JSON.toJSONString(request);
            sapRetrySaveRequest.setParam(requestJson);
            sapRetrySaveRequest.setMsg(message);
            sapRetrySaveRequest.setMessageId(request.getMessageHeader().getMessageId());
            //请求时间戳
            sapRetrySaveRequest.setRequestTime(sdo.getFeatures());
            sapRetrySaveRequest.setApiCode(SapApiCode.SAP007.getValue());
            sapRetrySaveRequest.setOutKey(sdo.getOutAllocateApplyOrderId());
            sapRetrySaveRequest.setStatus(RetryStatus.FAIL.getValue());
            sapRetryWriteService.save(sapRetrySaveRequest);
        }catch (Throwable e){
            log.error("sapRetrySaveError",e);
        }
    }

    boolean checkModifierTime(MnSapIf007SDO sdo){
        String modifierTime = epochCacheService.get(BcOtsConstants.REDIS_CACHE_CODE(),
                FORECAST_ORDER_CACHE_KEY + sdo.getOutAllocateApplyOrderId());
        String ext = sdo.getFeatures();
        if (org.apache.commons.lang3.StringUtils.isNotBlank(modifierTime)) {
            String[] modifierTimeArray = modifierTime.split("\\.");
            String[] extArray = ext.split("\\.");
            if (Long.parseLong(modifierTimeArray[0]) > Long.parseLong(extArray[0])) {
                return false;
            } else if (Long.valueOf(modifierTimeArray[0]).longValue() == Long.valueOf(extArray[0]).longValue()) {
                if (Long.parseLong(modifierTimeArray[1]) >= Integer.valueOf(extArray[1]).longValue()) {
                    return false;
                }
            }
        }
        return true;
    }
    void cache(String key,String time){
        if (org.apache.commons.lang3.StringUtils.isAnyBlank(key,time)){
            return;
        }
        epochCacheService.put(BcOtsConstants.REDIS_CACHE_CODE(),
                FORECAST_ORDER_CACHE_KEY + key,time,
                SAP_TIMESTAMP_CACHE_EXPIRE,
                TimeUnit.SECONDS);
    }
    private void setName(MnSapIf007SDO data, CreateForecastDTO createForecastDTO) {
        try {
            // 查询售达方信息
            SoldToPartyQueryAccurateRequest soldRequest = new SoldToPartyQueryAccurateRequest();
            Map<String, String> soldMap = new HashMap<>();
            soldMap.put("businessType", data.getProductGroupCode());
            soldMap.put("salesChannelCode", data.getSapChannel());
            soldMap.put("salesOrganizationCode", data.getSaleOrganizationCode());
            soldMap.put("soldToPartyCode", data.getSoldPartCode());
            soldRequest.setSoldToPartyAccurateQueryReq(Lists.newArrayList(soldMap));
            log.info("MnSapIf007V2ServiceImpl queryShipToPartyAndSoldToParty soldRequest={}", JSON.toJSONString(soldRequest));
            Result<List<SoldToPartyInternalResp>> listSoldResult = bcService.soldToPartyQueryAccurate(soldRequest);
            log.info("MnSapIf007V2ServiceImpl queryShipToPartyAndSoldToParty listSoldResult={}", JSON.toJSONString(listSoldResult));
            if (Objects.isNull(listSoldResult) || CollectionUtils.isEmpty(listSoldResult.getResult())) {
                return;
            }
            SoldToPartyInternalResp soldToParty = listSoldResult.getResult().get(0);
            createForecastDTO.setSalesDepartmentName(getName(soldToParty.getOuterSalesGroup(),soldToParty.getOuterSalesGroupCode()));
            createForecastDTO.setSalesChannelName(getName(soldToParty.getOuterSalesDepartment(),soldToParty.getOuterSalesDepartmentCode()));

        } catch (Exception e) {
            log.error("MnSapIf015V2ServiceImpl#queryShipToPartyAndSoldToParty error", e);
        }
    }
//    private void setName(CreateForecastDTO createForecastDTO,MnSapIf007SDO data) {
//        log.info("MnSapIf007V2ServiceImpl setName data={}",JSON.toJSONString(data));
//
//        try {
//            CustomerAddressSDO customerAddressSDO = queryShipToPartyAndSoldToParty(data,createForecastDTO);
//            if(Objects.isNull(customerAddressSDO)){
//                return;
//            }
//            IdQueryRequest idQueryRequest = new IdQueryRequest();
//            Result<com.epoch.app.crplatformenhance.sdo.OrganizationSDO> orgResult =null;
//            if(StringUtils.isNotEmpty(customerAddressSDO.getOrgSaleChannelCode())){
//                idQueryRequest.setId(customerAddressSDO.getOrgSaleChannelCode());
//                orgResult = organizationQueryService.getOrganizationDetail(idQueryRequest);
//                log.info("MnSapIf007V2ServiceImpl setName orgSaleChannelCode orgResult={}",JSON.toJSONString(orgResult));
//                if (orgResult != null && orgResult.getResult() != null) {
//                    createForecastDTO.setSalesChannelName(orgResult.getResult().getName());
//                } else {
//                    log.info("MnSapIf007V2ServiceImpl  setName orgSaleChannelCode not find sales department orgResult={}", JSON.toJSONString(orgResult));
//                }
//            }
//            if(StringUtils.isNotEmpty(customerAddressSDO.getOrgSaleDepartmentCode())){
//                idQueryRequest.setId(customerAddressSDO.getOrgSaleDepartmentCode());
//                orgResult = organizationQueryService.getOrganizationDetail(idQueryRequest);
//                log.info("MnSapIf007V2ServiceImpl setName orgSaleDepartmentCode orgResult={}",JSON.toJSONString(orgResult));
//                if (orgResult != null && orgResult.getResult() != null) {
//                    createForecastDTO.setSalesDepartmentName(orgResult.getResult().getName());
//                } else {
//                    log.info("MnSapIf007V2ServiceImpl setName orgSaleDepartmentCode not find sales department orgResult={}", JSON.toJSONString(orgResult));
//                }
//            }

//        }catch (Exception e){
//            log.info("MnSapIf007V2ServiceImpl setName error",e);
//        }
//    }
    private String getName(String name,String code){
        return name+"("+code+")";
    }
    private boolean checkSaleOrganizationCode(String saleOrganizationCode) {
        String saleOrganizations = OtsApplicationAdapterSdkConstants.BC_SALES_ORG_LIST();
        if (org.apache.commons.lang3.StringUtils.isEmpty(saleOrganizations)) {
            return false;
        }

        List<String> salesOrgList = Arrays.stream(saleOrganizations.split(","))
                .filter(code -> code.equals(saleOrganizationCode))
                .collect(Collectors.toList());
        return CollectionUtils.isNotEmpty(salesOrgList);
    }
    private CustomerAddressSDO pageQueryCustomerAddress(String addressCode,
                                                        String customerCode,
                                                        String orgSaleOrganizationCode,
                                                        String channelCode,
                                                        String itemGroup) {
        com.epoch.app.crplatformenhance.domain.customeraddress.dto.CustomerAddressLoadListRequest loadListRequest = new CustomerAddressLoadListRequest();
        loadListRequest.setAddressCode(addressCode);
        loadListRequest.setCustomerCode(customerCode);
        loadListRequest.setOrgSaleOrganizationCode(orgSaleOrganizationCode);
        loadListRequest.setChannelCode(channelCode);
        loadListRequest.setItemGroup(itemGroup);
        Result<List<CustomerAddress>> listResult = customerAddressService.loadCustomerAddressList(loadListRequest);
        if (Objects.isNull(listResult) || CollectionUtils.isEmpty(listResult.getResult())) {
            return null;
        }
        CustomerAddress customerAddress = listResult.getResult().get(0);

        CustomerAddressSDO customerAddressSDO = new CustomerAddressSDO();
        customerAddressSDO.setOrgSaleDepartmentCode(customerAddress.getOrgSaleDepartmentCode());
        customerAddressSDO.setOrgSaleChannelCode(customerAddress.getOrgSaleChannelCode());
        return customerAddressSDO;
    }
}
